<?php

namespace app\adminapi\controller;

use think\Controller;
use think\Request;

class Brand extends BaseApi
{
   
    public function index()
    {
        $params = input();
        $where = [];
        if(isset($params['cate_id']) && !empty($params['cate_id'])){
            $where = ['cate_id'=>$params['cate_id']];
            $list = \app\common\model\Brand::where($where)->field('id,name')->select();
         
        }else{
            if(isset($params['keyword']) && !empty($params['keyword'])){
                $where = [
                    't1.name'=>['like','%'. $params['keyword'].'%']
                ];
              
            }
            $list = \app\common\model\Brand::alias('t1')
            ->join('pyg_category t2','t1.cate_id = t2.id','left')
            ->where($where)
            ->field('t1.*, t2.cate_name')
            ->paginate(10);
         
        }
        $this->ok($list);
    }

    /**
     * 显示创建资源表单页.
     *
     * @return \think\Response
     */
    public function create()
    {
        //
    }

    /**
     * 保存新建的资源
     *
     * @param  \think\Request  $request
     * @return \think\Response
     */
    public function save(Request $request)
    {
        //接收参数
        $params = input();
        $this->ok($params)
        //参数检测
        $validate = $this->validate($params, [
            'name' => 'require',
            'cate_id' => 'require|integer|gt:0',
            'is_hot' => 'require|in:0,1',
            'sort' => 'require|between:0,9999'
        ]);
        if($validate !== true){
            $this->fail($validate);
        }
        //生成缩略图  /uploads/brand/20190716/1232.jpg
        if(isset($params['logo']) && !empty($params['logo']) && is_file('.' . $params['logo'])){
            \think\Image::open('.' . $params['logo'])->thumb(200,100)->save('.' . $params['logo']);
            $this->ok($params['logo']);
        }
        //添加数据
        $brand = \app\common\model\Brand::create($params, true);
        $info = \app\common\model\Brand::find($brand['id']);
        //返回数据
        $this->ok($info);
    }

    /**
     * 显示指定的资源
     *
     * @param  int  $id
     * @return \think\Response
     */
    public function read($id)
    {
        $info = \app\common\model\Brand::find($id);
        $this->ok($info);
    }

    /**
     * 显示编辑资源表单页.
     *
     * @param  int  $id
     * @return \think\Response
     */
    public function edit($id)
    {
        //
    }

    /**
     * 保存更新的资源
     *
     * @param  \think\Request  $request
     * @param  int  $id
     * @return \think\Response
     */
    public function update(Request $request, $id)
    {
        //
    }

    /**
     * 删除指定资源
     *
     * @param  int  $id
     * @return \think\Response
     */
    public function delete($id)
    {
        //
    }
}
